package com.it.App.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.App.eneity.User;
import com.it.App.mapper.UserMapper;
import com.it.App.service.UserService;
import com.it.App.token.JwtToken;
import com.it.App.utils.JwtUtil;
import com.it.App.vo.Response;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: CaoYouGen
 * @DateTime: 2023/11/28/11:13
 * @注释: TODO
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询用户信息
     *
     * @return 用户信息
     * @DateTime: 2023/11/28 14:01
     */
    public User selectUserByName(String username){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        return userMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public Response<?> login(User user) {
        // 检查用户名和密码是否为空
        if (ObjectUtil.isNull(user.getUsername()) || ObjectUtil.isNull(user.getPassword())) {
            return Response.error("账号密码不能为空");
        }
        // 获取Shiro的主体对象
        Subject subject = SecurityUtils.getSubject();

        // 生成JWT令牌
        String token = JwtUtil.createJWT(user.getUsername());

        // 创建JWT令牌对象
        JwtToken jwtToken = new JwtToken(token, user.getPassword());

        try {
            // 使用JWT令牌进行登录
            subject.login(jwtToken);
        } catch (UnknownAccountException e) {
            // 账号不存在异常
            return Response.error(401, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            // 密码错误异常
            return Response.error(402, "密码错误");
        }

        // 登录成功，查询用户信息
        User backUser = selectUserByName(user.getUsername());

        // 构建响应结果，包含用户信息和令牌
        Map<String, Object> map = new HashMap<>();
        map.put("user", backUser);
        map.put("token", token);

        return Response.ok(map);
    }
}
